package com.tyqx.biz.controller;

import com.tyqx.bean.model.EthPoolInfo;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class SendController {

    /*@Resource
    private SysResourceService sysResourceService;*/

    @RequestMapping("/send_{sendUrl}")
    public String sendUrl(@PathVariable("sendUrl")String sendUrl, HttpSession session){
        /*if(sendUrl.indexOf("index")!=-1&&session.getAttribute("dcepResourcesList")==null){
            SysUser sysUser=(SysUser) session.getAttribute("sysUser");
            Map<String,Object> param=new HashMap<>();
            param.put("userId",sysUser.getUserId());
            param.put("resId","0");

            List<SysResource> dcepResourceList=sysResourceService.queryTree(param);

            session.setAttribute("dcepResourceList",dcepResourceList);
        }*/

        return sendUrl.replace("_","/");
    }


    public static void main(String[] args) {
        String aa = "2c787cb600";
        Long x = Long.parseLong(aa,16);
        System.out.println(x);
        x = x + 1;
        String hex = x.toHexString(x);
        System.out.println(hex);

//        String url ="https://cn.etherscan.com/blocks";
//        String param="";
//        String sendGET = GetUrlUtil.GetUrl(url, param);
//        System.out.println(sendGET);

        //1.生成httpclient，相当于该打开一个浏览器
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        CloseableHttpResponse response1 = null;
        //2.创建get请求，相当于在浏览器地址栏输入 网址
        HttpGet request = new HttpGet("https://cn.etherscan.com/blocks");

        //
        HttpGet request1 = new HttpGet("https://cn.etherscan.com/");
        //设置请求头，将爬虫伪装成浏览器
        request.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");

        request1.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36");
//        HttpHost proxy = new HttpHost("60.13.42.232", 9999);
//        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
//        request.setConfig(config);
        try {
            //3.执行get请求，相当于在输入地址栏后敲回车键
            response = httpClient.execute(request);

            response1 = httpClient.execute(request1);

            //4.判断响应状态为200，进行处理
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //5.获取响应内容
                HttpEntity httpEntity = response.getEntity();
                String html = EntityUtils.toString(httpEntity, "utf-8");
                System.out.println(html);

                /**
                 * 下面是Jsoup展现自我的平台
                 */
                //6.Jsoup解析html
                Document document = Jsoup.parse(html);
                //像js一样，通过标签获取title
                //System.out.println(document.getElementsByTag("title").first());
                //像js一样，通过id 获取文章列表元素对象
                //Element postList = document.getElementById("post_list");
                Elements cardBody = document.getElementsByClass("card-body");
                //像js一样，通过class
                Elements tableResponsiveDiv = cardBody.get(0).getElementsByClass("table-responsive mb-2 mb-md-0");

                Element table = tableResponsiveDiv.get(0).getElementsByTag("table").get(0);

                Element tbody = table.getElementsByTag("tbody").first();

                System.out.println("tbody+================"+tbody);

                Elements trElements = tbody.children();

                List<EthPoolInfo> ethPoolInfoList = new ArrayList<>();

                for (Element tr : trElements) {
                    //像jquery选择器一样，获取文章标题元素
                    Elements tdElements = tr.children();

                    EthPoolInfo ethPoolInfo = new EthPoolInfo();

                    for (int i=0;i<tdElements.size();i++){
                        Element tdElement = tdElements.get(i);
                        switch (i){
                            case 0:
                                Long block = Long.parseLong(tdElement.getElementsByTag("a").text().trim());
                                ethPoolInfo.setBlock(block);
                                break;
                            case 1:
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                Date productDate = sdf.parse(tdElement.getElementsByTag("span").text().trim());
                                ethPoolInfo.setProductDate(productDate);
                                break;
                            case 3:
                                Long txn = Long.parseLong(tdElement.getElementsByTag("a").text().trim());
                                ethPoolInfo.setTxn(txn);
                                break;
                            case 4:
                                Long uncles = Long.parseLong(tdElement.text().trim());
                                ethPoolInfo.setUncles(uncles);
                                break;
                            case 5:
                                String miner = tdElement.getElementsByTag("a").text().trim();
                                ethPoolInfo.setMiner(miner);
                                break;
                            case 6:
                                String gasUsedText = tdElement.text().substring(0,tdElement.text().lastIndexOf("(")).trim();
                                String[] gasUsedArr= gasUsedText.split(",");
                                String gasUsedStr = "";
                                for (String gasUsdeIndex:
                                     gasUsedArr) {
                                    gasUsedStr = gasUsedStr + gasUsdeIndex;
                                }
                                Long gasUsed = Long.parseLong(gasUsedStr.trim());
                                String gasUsedScale = tdElement.getElementsByTag("span").text().trim();
                                ethPoolInfo.setGasUsed(gasUsed);
                                ethPoolInfo.setGasUsedScale(gasUsedScale);
                                break;
                            case 7:
                                String gasLimitText = tdElement.text().trim();
                                String[] gasLimitArr= gasLimitText.split(",");
                                String gasLimitStr = "";
                                for (String gasLimitIndex:
                                        gasLimitArr) {
                                    gasLimitStr = gasLimitStr + gasLimitIndex;
                                }
                                Long gasLimit = Long.parseLong(gasLimitStr);
                                ethPoolInfo.setGasLimit(gasLimit);
                                break;
                            case 8:
                                Double gasPrice = Double.parseDouble(tdElement.text().substring(0,tdElement.text().length()-4).trim());
                                ethPoolInfo.setGasPrice(gasPrice);
                                break;
                            case 9:
                                String  rewardStr = tdElement.text().trim();
                                rewardStr = rewardStr.substring(0,rewardStr.length()-5);
                                System.out.println(rewardStr);
                                rewardStr = rewardStr.trim();
                                Double reward = Double.parseDouble(rewardStr);
                                ethPoolInfo.setReward(reward);
                                break;
                        }
                    }
                    ethPoolInfoList.add(ethPoolInfo);
                }
                System.out.println(1);


            } else {
                //如果返回状态不是200，比如404（页面不存在）等，根据情况做处理，这里略
                System.out.println("返回状态不是200");
                System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            //6.关闭
            HttpClientUtils.closeQuietly(response);
            HttpClientUtils.closeQuietly(httpClient);
        }
    }

}
